package org.crh.appointment.web;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.crh.appointment.AppointmentService;
import org.crh.appointment.domain.AppointmentReq;
import org.crh.common.response.ResponseData;
import org.crh.common.response.impl.RuntimeResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("api")
public class AppointmentController {
    @Autowired
    private AppointmentService appointmentService;

    // 抢号接口
    @PostMapping("appointment/grab")
    @SentinelResource(
            value = "grab",
            blockHandler = "handleFlowLimit",  // 流控处理
            fallback = "handleSystemError"     // 降级处理
    )
    public ResponseEntity<ResponseData> grab(@RequestBody AppointmentReq appointmentReq) {
        return appointmentService.grabAppointment(appointmentReq);
    }

    // 流控处理（必须是public且参数一致）
    public ResponseEntity<ResponseData> handleFlowLimit(AppointmentReq appointmentReq, BlockException ex) {
        return ResponseEntity.ok(new RuntimeResponse(429, "当前排队人数过多，请稍后再试"));
    }

    // 降级处理（异常兜底）
    public ResponseEntity<ResponseData> handleSystemError(AppointmentReq appointmentReq, Throwable t) {
        return ResponseEntity.ok(new RuntimeResponse(500,"系统繁忙，请稍后重试"));
    }

}